/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import React from 'react';
import clsx from 'clsx';
import Link from '@docusaurus/Link';
import Heading from '@theme/Heading';
import styles from './styles.module.css';

import {Tags, TagList, type TagType} from '@site/src/data/tags';
import {sortBy} from '@site/src/utils/jsUtils';

function TagItem({
  tag,
}: {
  tag: string;
  key: string;
}) {
  const color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
  return (
    <li className={styles.tag} title={tag} key = {tag + color}>
      <span className={styles.textLabel}>{tag}</span>
      <span
      className={styles.colorLabel}
      style={{
        backgroundColor: color,
      }}
      />
    </li>
  );
}

function ShowcaseCardTag({tags}: {tags: TagType[]}) {
  const tagObjects = tags.map((tag) => ({tag, ...Tags[tag]}));

  // Keep same order for all tags
  const tagObjectsSorted = sortBy(tagObjects, (tagObject) =>
    TagList.indexOf(tagObject.tag),
  );

  return (
    <>
      {tagObjectsSorted.map((tagObject, index) => {
        return <TagItem key={index.toString()} {...tagObject} />;
      })}
    </>
  );
}


function ShowcaseCard({item}: any) {
  const {
    communityId,
    communityName,
    url,
    pic,
    profile,
    labelsArray,
  } = item;

  return (
    <li key={communityId} className="card shadow--md">
      <div className={clsx('card__image', styles.showcaseCardImage)}>
        <img src={pic} alt={communityName} />
      </div>
      <div className="card__body">
        <div className={clsx(styles.showcaseCardHeader)}>
          <Heading as="h4" className={styles.showcaseCardTitle}>
            <Link href={url} className={styles.showcaseCardLink}>
              {communityName}
            </Link>
          </Heading>
        </div>
        <p className={styles.showcaseCardBody}>{profile}</p>
      </div>
      <ul className={clsx('card__footer', styles.cardFooter)}>
          <ShowcaseCardTag tags={labelsArray} />
      </ul>
    </li>
  );
}

export default React.memo(ShowcaseCard);
